#!/usr/bin/perl

###########################################
#Author :  DebugProject _Brebion
#Created : 27/02/07
#Modified : 28/02/07
#Script : Selected line corresponding to chosen Stations
###########################################

#Check the command line
if(scalar(@ARGV) !=3){die "[way to use : <fileAll> <fileObervation> <fileStations>]"}	

$fileAll = $ARGV[0];
$fileObservation = $ARGV[1];
$fileStations = $ARGV[2];

#Check that exec_file1 exists
if(!(-e $fileAll)){die "[File <fileAll> doesn't exist]"}
if(!(-e $fileStations)){die "[File <fileStations> doesn't exist]"}

#Openinning handles
open(INPUT,"<$fileAll") || die "[Can't open <fileAll>]";
open(STATIONS,"<$fileStations") || die "[Can't open <fileStations>]";
open(OUTPUT,">$fileObservation");

#table of stations selected
@tabStation;

#function for creation of stations's table
while($ligne=<STATIONS>){
	if($ligne=~/^(.*)$/){
	@tabtemp=split(/;/, $1);
	push(@tabStation, @tabtemp);
	}
}

#creation of string including the elements of the table
$nb=scalar(@tabStation);
for($i=0;$i<$nb-1;$i++){
	$listPost .=@tabStation[$i];
	$listPost .=",";
}
$listPost .=@tabStation[$nb-1];

close STATIONS;

#function that return 1 if the station is in the table and 0 if it isn't
sub findTabl {
	$nbElement=scalar(@_);
	$stationFind=$_[$nbElement-1];
	for($i=0;$i<$nbElement-1;$i++){
		
		if($_[$i]==$stationFind){
			return 1;
		}
	}
	return 0;
}



#glance through fileAll and write the fileObservation
while($ligne=<INPUT>){
	if($ligne=~/^\<log\s*execID=\s*(.*)\s*pIDlist=\s*(.*)\s*\>\s*$/){
		#rewrite the line where the posts are writting with only the sected posts
		print OUTPUT ("<log execID=",$1,"pIDlist=\"{", $listPost,"}\">\n\n");

	}elsif($ligne=~/^\<msg\stype="\w+"\s*sender="\s*(\w+)\s*"\s*rcver="\s*(\w+)\s*".*\>.*\<\/msg\>\s*$/){
		if((findTabl(@tabStation, $1))||(findTabl(@tabStation, $2))){
			#Only rewrite the line who have the sected posts 
			print OUTPUT ($ligne);
		}
	}else {
		#rewrite the other line
		print OUTPUT ($ligne);
		}
}

#Closing handles 		
close OUTPUT;
close INPUT;
